//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { get_admin_session, get_admin_perm } from '@/api/admin_auth';
import type { AdminPermInfo } from '@/api/admin_auth';
import type { TagInfo, WhiteUserInfo } from "@/api/roadmap_admin";
import { list_white_user, remove_white_user, list_tag } from "@/api/roadmap_admin";
import { Button, Card, message, Modal, Popover, Space, Table } from "antd";
import { request } from "@/utils/request";
import EditWhiteUserModal from "./components/EditWhiteUserModal";
import type { ColumnsType } from 'antd/lib/table';
import { getSimpleUerName, getUserType, USER_TYPE_ATOM_GIT, USER_TYPE_GIT_CODE, USER_TYPE_GITEE, USER_TYPE_INTERNAL } from "@/api/user";
import { MoreOutlined } from "@ant-design/icons";

const PAGE_SIZE = 20;

const RoadmapWhiteUserAdminList = () => {
    const [permInfo, setPermInfo] = useState<AdminPermInfo | null>(null);

    const [tagInfoList, setTagInfoList] = useState<TagInfo[]>([]);

    const [whiteUserList, setWhiteUserList] = useState<WhiteUserInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [showAddModal, setShowAddModal] = useState(false);
    const [updateUserInfo, setUpdateUserInfo] = useState<WhiteUserInfo | null>(null);
    const [removeUserInfo, setRemoveUserInfo] = useState<WhiteUserInfo | null>(null);

    const loadTagInfoList = async () => {
        const sessionId = await get_admin_session();
        const res = await request(list_tag({
            session_id: sessionId,
        }));
        setTagInfoList(res.tag_list);
    };

    const loadWhiteUserList = async () => {
        const sessionId = await get_admin_session();
        const res = await request(list_white_user({
            session_id: sessionId,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setWhiteUserList(res.white_user_list);
    };

    const removeWhiteUser = async () => {
        if (removeUserInfo == null) {
            return;
        }
        const sessionId = await get_admin_session();
        await request(remove_white_user({
            session_id: sessionId,
            target_user_id: removeUserInfo.user_id,
        }));
        await loadWhiteUserList();
        message.info("删除成功");
        setRemoveUserInfo(null);
    };

    const columns: ColumnsType<WhiteUserInfo> = [
        {
            title: "用户类型",
            width: 90,
            render: (_, row: WhiteUserInfo) => {
                const userType = getUserType(row.user_name);
                if (userType == USER_TYPE_INTERNAL) {
                    return "内部用户";
                } else if (userType == USER_TYPE_ATOM_GIT) {
                    return "AtomGit用户";
                } else if (userType == USER_TYPE_GIT_CODE) {
                    return "GitCode用户";
                } else if (userType == USER_TYPE_GITEE) {
                    return "Gitee用户";
                }
                return "";
            },
        },
        {
            title: "用户账号",
            width: 100,
            render: (_, row: WhiteUserInfo) => getSimpleUerName(row.user_name),
        },

        {
            title: "默认渠道",
            width: 90,
            render: (_, row: WhiteUserInfo) => (
                <>
                    {tagInfoList.filter(tagInfo => tagInfo.tag == row.default_tag).map(tagInfo => (
                        <span key={tagInfo.tag}>{tagInfo.name}</span>
                    ))}
                </>
            )
        },
        {
            title: "用户备注",
            dataIndex: "user_desc",
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: WhiteUserInfo) => (
                <Space>
                    <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={!(permInfo?.roadmap_perm.update_white_user ?? false)}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setUpdateUserInfo(row);
                        }}>修改</Button>
                    <Popover placement="bottom" trigger="click" content={
                        <Space direction="vertical">
                            <Button type="link" danger disabled={!(permInfo?.roadmap_perm.remove_tag ?? false)}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setRemoveUserInfo(row);
                                }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            ),
        }
    ];

    useEffect(() => {
        loadTagInfoList();
        get_admin_perm().then(res => setPermInfo(res));
    }, []);

    useEffect(() => {
        loadWhiteUserList();
    }, [curPage]);

    return (
        <Card title="路线图白名单" bodyStyle={{ height: "calc(100vh - 90px)", overflowY: "scroll" }}
            extra={
                <Button type="primary" disabled={!(permInfo?.roadmap_perm.add_white_user ?? false)}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowAddModal(true);
                    }}>增加</Button>
            }>
            <Table rowKey="user_id" dataSource={whiteUserList} columns={columns}
                pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }} />
            {showAddModal == true && (
                <EditWhiteUserModal onCancel={() => setShowAddModal(false)} onOk={() => {
                    setShowAddModal(false);
                    if (curPage != 0) {
                        setCurPage(0);
                    } else {
                        loadWhiteUserList();
                    }
                }} />
            )}
            {updateUserInfo != null && (
                <EditWhiteUserModal whiteUser={updateUserInfo} onCancel={() => setUpdateUserInfo(null)}
                    onOk={() => {
                        setUpdateUserInfo(null);
                        loadWhiteUserList();
                    }} />
            )}
            {removeUserInfo != null && (
                <Modal open title="删除白名单用户" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveUserInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeWhiteUser();
                    }}>
                    是否删除白名单用户&nbsp;{getSimpleUerName(removeUserInfo.user_name)} {removeUserInfo.user_display_name}&nbsp;?
                </Modal>
            )}
        </Card>
    );
};

export default RoadmapWhiteUserAdminList;